package com.waypolice.manager.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.waypolice.base.BaseController;
import com.waypolice.common.pojo.TaotaoResult;
import com.waypolice.common.utils.IoUtils;
import com.waypolice.manager.service.ActivitiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.Model;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述:
 *
 * @author zyp
 * @description 工作流模型控制器
 * @create 2019-02-25 14:25
 */
@Controller
@Api(value = "工作流模型控制器", description = "工作流的创建、部署、下载")
@RequestMapping(value="/pcwindow")
public class ActModelAction extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ActModelAction.class);

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private ActivitiService activitiService;

    /**
     * @author:zyp
     * @description 跳转工作流模型页面
     * @date: 2019/2/25 15:38
     * @return
     */
    @ApiOperation(value = "工作流模型跳转")
    @RequiresPermissions("upms:model:read")
    @RequestMapping(value = "/toActModel", method = RequestMethod.GET)
    public String toActModel(HttpServletResponse response,
                               HttpServletRequest request) {
        return "/activitiManager/actModel";
    }

    /**
     * @author:zyp
     * @description 获取工作流模型
     * @date: 2019/2/25 15:38
     * @return 
     */
    @ApiOperation(value = "获取工作流模型")
    @RequestMapping(value = "/getActModel", method = RequestMethod.GET)
    @RequiresPermissions("upms:model:read")
    @ResponseBody
    public Object getActModel(@RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
                              @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
                              @RequestParam(required = false, defaultValue = "", value = "search") String search,
                              @RequestParam(required = false, value = "sort") String sort,
                              @RequestParam(required = false, value = "order") String order) {
        Map<String, Object> result = new HashMap<>(2);
        List<Model> rows = repositoryService.createModelQuery().list();
        List<Model>  finalList = activitiService.pagingActModel(rows,offset,limit,search);
        result.put("rows",finalList);
        result.put("total",rows.size());
        return result;
    }

    /**
     * @author:zyp
     * @description 创建流程模型
     * @date: 2019/2/25 16:09
     * @return 
     */
    @ApiOperation(value = "创建流程模型")
    @RequestMapping(value = "/createModel", method = RequestMethod.POST)
    @RequiresPermissions("upms:model:create")
    @ResponseBody
    public Object createModel(@RequestParam("name") String name, @RequestParam("key") String key, @RequestParam("description") String description,
                         HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Model> list = repositoryService.createModelQuery().list();
            for(Model model : list){
                String key1 = model.getKey();
                if(key.equals(key1)){
                    return new TaotaoResult(0,"key值不能重复",null);
                }
            }
            ObjectMapper objectMapper = new ObjectMapper();
            ObjectNode editorNode = objectMapper.createObjectNode();
            editorNode.put("id", "canvas");
            editorNode.put("resourceId", "canvas");
            ObjectNode stencilSetNode = objectMapper.createObjectNode();
            stencilSetNode.put("namespace", "http://b3mn.org/stencilset/bpmn2.0#");
            editorNode.set("stencilset", stencilSetNode);
            Model modelData = repositoryService.newModel();

            ObjectNode modelObjectNode = objectMapper.createObjectNode();
            modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, name);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
            description = StringUtils.defaultString(description);
            modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, description);
            modelData.setMetaInfo(modelObjectNode.toString());
            modelData.setName(name);
            modelData.setKey(StringUtils.defaultString(key));
            repositoryService.saveModel(modelData);
            repositoryService.addModelEditorSource(modelData.getId(), editorNode.toString().getBytes("utf-8"));
            return  new TaotaoResult(200,"保存成功",modelData.getId());
        } catch (Exception e) {
            logger.error("创建模型失败：", e);
            return  null;
        }
    }

    /**
     * @author:zyp
     * @description 到处model模型
     * @date: 2019/2/25 17:40
     * @return 
     */
    @ApiOperation(value = "导出model模型")
    @RequiresPermissions("upms:model:read")
    @RequestMapping(value = "export/{modelId}/{type}")
    public void export(@PathVariable("modelId") String modelId, @PathVariable("type") String type, HttpServletResponse response) {
        BufferedOutputStream out = null;
        ByteArrayInputStream in = null;
        try {
            Model modelData = repositoryService.getModel(modelId);
            BpmnJsonConverter jsonConverter = new BpmnJsonConverter();
            byte[] modelEditorSource = repositoryService.getModelEditorSource(modelData.getId());
            JsonNode editorNode = new ObjectMapper().readTree(modelEditorSource);
            BpmnModel bpmnModel = jsonConverter.convertToBpmnModel(editorNode);
            // 处理异常
            if (bpmnModel.getMainProcess() == null) {
                response.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());
                response.getOutputStream().println("no main process, can't export for type: " + type);
                response.flushBuffer();
                return;
            }
            String filename = "";
            byte[] exportBytes = null;
            String mainProcessId = bpmnModel.getMainProcess().getId();
            if (type.equals("bpmn")) {
                BpmnXMLConverter xmlConverter = new BpmnXMLConverter();
                exportBytes = xmlConverter.convertToXML(bpmnModel);
                filename = mainProcessId + ".bpmn20.xml";
            } else if (type.equals("json")) {
                exportBytes = modelEditorSource;
                filename = mainProcessId + ".json";
            }
            in = new ByteArrayInputStream(exportBytes);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + filename);
            int len = 0;
            byte[] bytes = new byte[5120];
            out = new BufferedOutputStream(response.getOutputStream());
            while ((len = in.read(bytes)) != -1) {
                out.write(bytes, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            logger.error("导出model的xml文件失败：modelId={}, type={}", modelId, type, e);
        }finally {
            IoUtils.closeInputStram(in);
            IoUtils.closeOutputStram(out);
        }
    }

    /**
     * @author:zyp
     * @description 删除model模型
     * @date: 2019/2/25 17:46
     * @return 
     */
    @ApiOperation(value = "删除模型")
    @RequiresPermissions("upms:model:delete")
    @RequestMapping(value = "delModel/{modelIds}")
    @ResponseBody
    public Object delete(@PathVariable("modelIds") String modelIds) {
        int count ;
        if (StringUtils.isBlank(modelIds)) {
            count = 0;
        }else{
            String[] idArray = modelIds.split("-");
            for (String idStr : idArray) {
                if (StringUtils.isBlank(idStr)) {
                    continue;
                }
                repositoryService.deleteModel(idStr);
            }
            count = 1 ;
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("state",1);
        jsonObject.put("message","SUCCESS");
        jsonObject.put("data",count);
        return jsonObject;
    }

    /**
     * @author:zyp
     * @description 根据modelId部署流程
     * @date: 2019/2/26 8:42
     * @return 
     */
    @ApiOperation(value = "根据ModelId部署流程")
    @RequiresPermissions("upms:model:deploy")
    @RequestMapping(value = "/deploy/{modelIds}")
    @ResponseBody
    public List<String> deploy(@PathVariable("modelIds") String modelIds, RedirectAttributes redirectAttributes) {
        //部署失败的模型
        List<String> countFail = new ArrayList<String>();
        if (StringUtils.isBlank(modelIds)) {
            return countFail;
        }else{
            String[] idArray = modelIds.split("-");
            for (String modelId : idArray) {
                if (StringUtils.isBlank(modelId)) {
                    continue;
                }
                try {
                    Model modelData = repositoryService.getModel(modelId);
                    ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(modelData.getId()));
                    byte[] bpmnBytes = null;
                    BpmnModel model = new BpmnJsonConverter().convertToBpmnModel(modelNode);
                    bpmnBytes = new BpmnXMLConverter().convertToXML(model);
                    String processName = modelData.getName() + ".bpmn20.xml";
                    Deployment deployment = repositoryService.createDeployment().name(modelData.getName()).addString(processName, new String(bpmnBytes, "UTF-8")).deploy();
                } catch (Exception e) {
                    countFail.add(modelId);
                    logger.error("根据模型部署流程失败：modelId={}", modelId, e);
                }
            }
            return countFail;
        }
    }
}